package no.gnet.s10.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import no.gnet.s10.broker.Broker;
import no.gnet.util.Constants;
import no.gnet.util.S10Props;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class for Servlet: Upload
 *
 * @web.servlet
 *   name="Upload"
 *   display-name="Upload" 
 *
 * @web.servlet-mapping
 *   url-pattern="/Upload"
 *  
 */
 public class Upload extends GNetController{
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public Upload() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().println("GET not supported");
		response.getWriter().close();
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!ServletFileUpload.isMultipartContent(request)){
			response.getWriter().println("Not multipart content");
			response.getWriter().close();
			return;
		}
		System.out.println("Retrieving file..");
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
			doError(request, response, "Failed parsing upload request", e.getMessage());
			return;
		}
		System.out.println("Retrieving file.. iterating items");
		if(items!=null && items.size()>0){
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = (FileItem) iter.next();
			    if (item.isFormField()) {
			        String name = item.getFieldName();
			        String value = item.getString();
			    	System.out.println("name="+name+",value="+value);
			    } else {
			        String fieldName = item.getFieldName();
			        String fileName = item.getName();
			        String contentType = item.getContentType();
			        boolean isInMemory = item.isInMemory();
			        long sizeInBytes = item.getSize();
			        System.out.println("fieldName="+fieldName+",fileName="+fileName+
			        		", contentType="+contentType+",isInMemory="+isInMemory+
			        		", sizeInBytes"+sizeInBytes);
			        String filenametowrite=Broker.getNewImgFileName();
			        String path = (String)S10Props.getInstance().getProps().
			        				get(Constants.IMAGES_HOME);
			        filenametowrite=path+"/"+filenametowrite;
			        System.out.println("image-name: "+filenametowrite);
			        InputStream in = item.getInputStream();
			        int len=0;
			        byte [] bytes = new byte[4096];
			        FileOutputStream fos = new FileOutputStream(filenametowrite);
			        while((len=in.read(bytes))>0){
			        	fos.write(bytes, 0, len);
			        }
			        fos.close();
			        in.close();
			        System.out.println("Wrote stream to file");
			    }
			}
			try {
				handleRequest(request, response, "unknown");
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServletException("Failed uploading");
			}
			
		}
		
		
	}   	  	    
}